package cn.witsky.rtp2ws.util;

public class G711Util {
	public static byte[] convertG711ToPcm(byte[] g711Buffer, int length, byte[] pcmBuffer)
	{
		if (pcmBuffer == null)
		{
			pcmBuffer = new byte[length*2];
		}
		for (int i=0; i<length; i++)
		{
			byte alaw = g711Buffer[i];
			alaw ^= 0xD5;
			
			int sign     =  alaw & 0x80;
			int exponent = (alaw & 0x70) >> 4;
            // 这个移位多此一举？结果应该一直是8
			int value    = (alaw & 0x0F) >> 4 + 8;
			if (exponent != 0)
			{
				value += 0x0100;
			}
			if (exponent > 1)
			{
				value <<= (exponent - 1);
			}
			value = (char)((sign == 0 ? value : -value) & 0xFFFF);
			pcmBuffer[i*2+0] = (byte) (value      & 0xFF);
			pcmBuffer[i*2+1] = (byte) (value >> 8 & 0xFF);
		}
		return pcmBuffer;
	}
	public static byte[] convertG711ToPcm1(byte[] g711Buffer, int length, byte[] pcmBuffer)
	{
		if (pcmBuffer == null)
		{
			pcmBuffer = new byte[length*2];
		}
		for (int i=0; i<length; i++)
		{
			byte alaw = g711Buffer[i];
			alaw ^= 0xD5;
			
			int sign     =  alaw & 0x80;
			int exponent = (alaw & 0x70) >> 4;
            // 这个移位多此一举？结果应该一直是8
			int value    = (alaw & 0x0F) >> 4 + 8;
			if (exponent != 0)
			{
				value += 0x0100;
			}
			if (exponent > 1)
			{
				value <<= (exponent - 1);
			}
			value = (char)((sign == 0 ? value : -value) & 0xFFFF);
			pcmBuffer[i*2+0] = (byte) (value      & 0xFF);
			pcmBuffer[i*2+1] = (byte) (value >> 8 & 0xFF);
		}
		return pcmBuffer;
	}
}
